package com.california.pay.facade.impl;

import com.alibaba.fastjson.JSON;
import com.california.pay.config.CommonErrors;
import com.california.pay.config.FacadeServiceTemplate;
import com.california.pay.exception.BusinessException;
import com.california.pay.facade.TerminalManagerFacade;
import com.california.pay.model.PersonOrderPayRsp;
import com.california.pay.persist.domain.TerminalLogin;
import com.california.pay.persist.mapper.TerminalLoginMapper;
import com.california.pay.result.CommonResult;
import com.california.pay.service.BaseService;
import com.california.pay.service.TerminalLoginService;
import com.california.pay.socket.NettyChannelMap;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


@Slf4j
public class TerminalManagerFacadeImpl implements TerminalManagerFacade {
    private String simpleClassName = this.getClass().getSimpleName();
    @Autowired
    private FacadeServiceTemplate serviceTemplate;
    @Autowired
    private TerminalLoginService loginService;
    @Autowired
    private TerminalLoginMapper loginMapper;

    @Override
    public CommonResult<?> terminalLogout(String channelUserId) {
        BaseService.initTraceId(simpleClassName + "#terminalLogout");
        String facadeName = "[终端登出#TerminalManagerFacadeImpl#terminalLogout]接口";
        log.info("请求{}, 请求报文={}", facadeName, JSON.toJSONString(channelUserId));

        CommonResult<PersonOrderPayRsp> result = serviceTemplate.execute(facadeName, () -> {
            TerminalLogin terminalLogin = loginMapper.selectOneByChannelUserId(channelUserId);
            if (terminalLogin == null){
                throw new BusinessException(CommonErrors.UNDEFINED, "未找到对应的登录终端");
            }

            String nettyChannelId = terminalLogin.getNettyChannelId();
            Channel channel = NettyChannelMap.getChannelByName(nettyChannelId);

            if (channel != null){
                channel.close();
            }

            loginService.logout(channel, nettyChannelId);
            return CommonResult.success();
        });

        log.info("请求{}, 应答报文={}", facadeName, JSON.toJSONString(result));
        return result;
    }
}
